let curPage = 1;
let pageSize = 10;
layui.use(['laydate','form','laypage', 'layer'], function(){
    let laydate = layui.laydate;
    let form = layui.form;
    page()
    //执行一个laydate实例
    laydate.render({
        elem: '#start' //指定元素
    });

    //执行一个laydate实例
    laydate.render({
        elem: '#end' //指定元素
    });
//监听提交
    form.on('submit(sreach)',
        function () {
            page();
            return false;
        });
});
function getHobby() {
    let value = [];
    $('input[name=hobby]:checked').each(function () {
        //这里用所选复选框或运算后的值
        value.push($(this).val());
    });
    return value;
}
function getSearchData() {
    return {
        username: $("#username").val(),
        createTime: $("#start").val(),
        updateTime: $("#end").val(),
        phone: $("#phone").val(),
        sex: $("#sex").val(),
        hobby: getHobby().toLocaleString(),
    };
}
function getCount(json) {
    let count = 0;
    $.ajax({
        url: 'http://localhost:11111/back/user/count',//地址：访问后台的地址
        data: {val : JSON.stringify(getSearchData(json))},//前端传递给后台的数据
        type: 'get',
        async: false,
        dataType: 'json',//是后端传递到前端的数据格式
        xhrFields:{
            withCredentials:true
        },
        beforeSend: function(xhr) {
                    let token = localStorage.getItem('token');
                    xhr.setRequestHeader("Authorization", token);
        },
        success: function (data) {//后端给前端的一个反馈
            count = data;
        }
    });
    return count;
}
function setList(data) {
    let html = '';
    for (let i = 0; i < data.length; i++) {
        html += '<tr>\n' +
            '                            <td>' + data[i].id + '</td>\n' +
            '                            <td>' + data[i].username + '</td>\n' +
            '                            <td>' + setUndefinedNull(data[i].sex) + '</td>\n' +
            '                            <td>' + setUndefinedNull(data[i].phone) + '</td>\n' +
            '                            <td>' + setUndefinedNull(data[i].birthday) + '</td>\n' +
            '                            <td>' + setUndefinedNull(data[i].hobby) + '</td>\n' +
            '                            <td class="td-status">\n' +
            '                                <span class="layui-btn layui-btn-normal layui-btn-mini">' + (data[i].enable == 1 ? "已启用" : "已停用") + '</span></td>\n' +
            '                            <td class="td-manage">\n' +
            '                                <a onclick="member_stop(this,' + data[i].id + ')" href="javascript:;" title="' + (data[i].enable == 1 ? "启用" : "停用") + '">\n' +
            '                                    <i class="layui-icon">&#xe601;</i>\n' +
            '                                </a>\n' +
            '                                <a title="编辑" onclick="edit(' + data[i].id + ')"\n' +
            '                                   href="javascript:;">\n' +
            '                                    <i class="iconfont">&#xe68b;</i>\n' +
            '                                </a>\n' +
            '                                <a onclick="xadmin.open(\'修改密码\',\'member-password.html\',600,400)" title="修改密码"\n' +
            '                                   href="javascript:;">\n' +
            '                                    <i class="layui-icon">&#xe631;</i>\n' +
            '                                </a>\n' +
            '                                <a title="删除" onclick="member_del(this,' + data[i].id + ')" href="javascript:;">\n' +
            '                                    <i class="layui-icon">&#xe640;</i>\n' +
            '                                </a>\n' +
            '                            </td>\n' +
            '                        </tr>';
    }
    $("#tbody").html(html);
}
function findAll(obj) {
    curPage = obj.curr;
    pageSize = obj.limit;
    let data = myAjax('http://localhost:11111/back/user/get', {startPage: (curPage-1)*pageSize,
        pageSize: pageSize, val : JSON.stringify(getSearchData())}, 'get');
    // console.log(JSON.stringify(data))
    if(data.code !== 0){
        layer.msg(data.message, {icon: 2, time: 1000});
        return false
    }
    setList(data.data);
}
    function setUndefinedNull(data) {
        return data == undefined ? "" : data;
    }
function page(){
    layui.use(['laydate','form','laypage', 'layer'], function(){
        let laypage = layui.laypage
            ,layer = layui.layer;
        laypage.render({
            contentType:"application/json;charset=utf-8"
            ,elem: 'page'
            ,count: getCount(getSearchData())
            ,layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
            ,jump: function(obj){
                findAll(obj);
            }
        });
    })
}
/*用户-删除*/
function member_del(obj, id) {
    layer.confirm('确认要删除吗？', function (index) {
        //发异步删除数据
        $.ajax({
            url: 'http://localhost:11111/back/user/del',//地址：访问后台的地址
            data: {id: id},//前端传递给后台的数据
            type: 'post',
            dataType: 'json',//是后端传递到前端的数据格式
            beforeSend: function(xhr) {
                        let token = window.localStorage.getItem('token');
                        xhr.setRequestHeader("Authorization", token);
            },
            success: function (data) {//后端给前端的一个反馈
                console.log(data);
                if (data.code === 0) {
                    $(obj).parents("tr").remove();
                    layer.msg('已删除!', {icon: 1, time: 1000});
                    window.location.reload();
                }
            }

        });

    });
}
/*用户-编辑*/
function edit(id) {
    let data = myAjax('http://localhost:11111/back/user/goEdit',{id:id},'post')
    if(data.code !== 0){
        alert(data.msg)
    }
    sessionStorage.setItem("data", JSON.stringify(data.data));
    xadmin.open('编辑', 'member-edit.html', 600, 400);
}
/*用户-停用*/
function member_stop(obj, id) {
    layer.confirm('确认要' + $(obj).attr('title') + '吗？', function (index) {
        //发异步把用户状态进行更改
        let data = myAjax("http://localhost:11111/back/user/enable", {id: id}, "post");
        if (data.code === 0) {
            if ($(obj).attr('title') == '启用') {


                $(obj).attr('title', '停用')
                $(obj).find('i').html('&#xe62f;');

                $(obj).parents("tr").find(".td-status").find('span').removeClass('layui-btn-disabled').html('已启用');
                layer.msg('已启用!', {icon: 5, time: 1000});


            } else {
                $(obj).attr('title', '启用')
                $(obj).find('i').html('&#xe601;');
                $(obj).parents("tr").find(".td-status").find('span').addClass('layui-btn-disabled').html('已停用');
                layer.msg('已停用!', {icon: 6, time: 1000});
            }
        } else {
            layer.msg('更新失败!', {icon: 2, time: 1000});
        }


    });
}